package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.di.component.DaggerLingLiaoShenQingQingDanComponent;
import com.example.administrator.printoutindemo.di.module.LingLiaoShenQingQingDanModule;
import com.example.administrator.printoutindemo.mvp.contract.LingLiaoShenQingQingDanContract;
import com.example.administrator.printoutindemo.mvp.presenter.LingLiaoShenQingQingDanPresenter;
import com.example.administrator.printoutindemo.mvp.ui.entity.LingLiaoShenQingQingDan;
import com.example.administrator.printoutindemo.mvp.ui.entity.OutStorageCheckItem;
import com.example.administrator.printoutindemo.mvp.ui.entity.StoreOutStorageMaterialCheckList;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import com.jess.arms.base.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_LING_LIAO_SHEN_QING_QING_DAN)
public class LingLiaoShenQingQingDanActivity extends BaseActivity<LingLiaoShenQingQingDanPresenter> implements LingLiaoShenQingQingDanContract.View {


    @BindView(R.id.tv_ling_liao_dan_hao)
    TextView tvLingLiaoDanHao;
    @BindView(R.id.tv_xiang_mu_ming_cheng)
    TextView tvXiangMuMingCheng;
    @BindView(R.id.tv_xiang_mu_bian_hao)
    TextView tvXiangMuBianHao;
    @BindView(R.id.tv_shen_qing_ren)
    TextView tvShenQingRen;
    @BindView(R.id.tv_ling_liao_ren)
    TextView tvLingLiaoRen;
    @BindView(R.id.tv_shen_he_zhuang_tai)
    TextView tvShenHeZhuangTai;
    @BindView(R.id.tv_shen_he_ren)

    TextView tvShenHeRen;
    @BindView(R.id.tv_ling_liao_ren_dian_hua)
    TextView tvLingLiaoRenDianHua;
    @BindView(R.id.tv_dao_huo_di_dian)
    TextView tvDaoHuoDiDian;
    private String out_storagelist_batchid;
    private static final int LOGINSUCCESS = 0;
    private static final int NETWORKERROR = 2;
    private static final int SYSERROR = 3;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLingLiaoShenQingQingDanComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .lingLiaoShenQingQingDanModule(new LingLiaoShenQingQingDanModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_ling_liao_shen_qing_qing_dan; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.ling_liao_shen_qing));
//        getLingLiaoShenQingQingDanData();


        OutStorageCheckItem outStorageCheckItem = (OutStorageCheckItem) getIntent().getSerializableExtra("outStorageCheckItem");

        tvLingLiaoDanHao.setText(outStorageCheckItem.getBatchId());
        tvXiangMuMingCheng.setText(outStorageCheckItem.getProjectName());
        tvXiangMuBianHao.setText(outStorageCheckItem.getProid());
        tvDaoHuoDiDian.setText(outStorageCheckItem.getStoreName());
        tvShenQingRen.setText(outStorageCheckItem.getApplyUserName());
//        tvShenHeRen.setText(outStorageCheckItem.getOut_storagelist_batchid());
        tvShenHeZhuangTai.setText(outStorageCheckItem.getCheckStatus());
        tvLingLiaoRen.setText(outStorageCheckItem.getReceiveUserName());
        tvLingLiaoRenDianHua.setText(outStorageCheckItem.getRecievePhone());

    }

    private void getLingLiaoShenQingQingDanData() {
//        mPresenter.getLingLiaoShenQingQingDanData();

        out_storagelist_batchid = mSharedPreferencesHelper.getString(BaseConstants.BATCH_ID);
        if (!TextUtils.isEmpty(out_storagelist_batchid)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);

                    try {

                        if (getCheckMaterial(out_storagelist_batchid)) {
                            Message m = new Message();
                            m.what = LOGINSUCCESS;
                            hanlder.sendMessage(m);
                        }
                    } catch (Exception e) {
                        Message m = new Message();
                        m.what = SYSERROR;
                        hanlder.sendMessage(m);
                    }

                }
            }).start();
        }

    }

    @SuppressLint("HandlerLeak")
    private final Handler hanlder = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LOGINSUCCESS:

//                    Tools.showDialogInfo(StoreSubmitProject3Activity.this, store_sub3_btn_submit, "申请出库成功！");
//                    ArmsUtils.makeText(getContext(), "申请出库成功！");
//                    Intent in = new Intent();
//                    in.setClass(StoreSubmitProject3Activity.this, StoreSubmitProject1Activity.class);
//                    in.setClass(getContext(), LingLiaoShenQingQingDanActivity.class);
//                    startActivity(in);
//                    LoadingDialogUtil.dismissDialog();
                    break;

                case NETWORKERROR:

                    Toast.makeText(getContext(), "网络或系统异常!", Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();
                    break;
                case SYSERROR:

                    Toast.makeText(getContext(), "系统异常!", Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();
                    break;

                default:
                    LoadingDialogUtil.dismissDialog();
                    break;
            }

        }
    };

    @Override
    public void getLingLiaoShenQingQingDanDataSuccess(LingLiaoShenQingQingDan entityData) {


    }

    /**
     * 申请出库物料明细
     *
     * @param out_storagelist_batchid
     * @return
     */
    private boolean getCheckMaterial(String out_storagelist_batchid) {

        boolean bl = false;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetCheckMaterial";


            String url = "http://" + mSharedPreferencesHelper.getString(BaseConstants.IP) + ":"
                    + mSharedPreferencesHelper.getString(BaseConstants.PORT)
                    + "/StoreService.asmx";
            // // 10.0.2.2
            // 为Android模拟器的本地(localhost)IP
            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("out_storagelist_batchid", out_storagelist_batchid);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                String result = response.toString();


                if (!TextUtils.isEmpty(result)) {
                    // int id = Integer.parseInt(response.toString());
                    bl = true;
                    Gson gson = new Gson();
                    List<StoreOutStorageMaterialCheckList> storeOutStorageMaterialCheckLists = (List<StoreOutStorageMaterialCheckList>) gson.fromJson(result, StoreOutStorageMaterialCheckList.class);

                    if (storeOutStorageMaterialCheckLists == null && storeOutStorageMaterialCheckLists.size() > 0) {

                        tvLingLiaoDanHao.setText(storeOutStorageMaterialCheckLists.get(0).getOut_storagelist_batchid());
                        tvXiangMuMingCheng.setText(storeOutStorageMaterialCheckLists.get(0).getProjectname());
                        tvXiangMuBianHao.setText(storeOutStorageMaterialCheckLists.get(0).getProid());
                        tvDaoHuoDiDian.setText(storeOutStorageMaterialCheckLists.get(0).getOut_storagelist_batchid());
                        tvShenQingRen.setText(storeOutStorageMaterialCheckLists.get(0).getUser_name());
                        tvShenHeRen.setText(storeOutStorageMaterialCheckLists.get(0).getOut_storagelist_batchid());
                        tvShenHeZhuangTai.setText(storeOutStorageMaterialCheckLists.get(0).getDeal_status());
                        tvLingLiaoRen.setText(storeOutStorageMaterialCheckLists.get(0).getReceive_username());
                        tvLingLiaoRenDianHua.setText(storeOutStorageMaterialCheckLists.get(0).getReceive_phone());
                    }

                }
            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }


        return bl;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
